
//腾讯面试题
//学习 std::choron使用方式及限流；
#include <chrono>
#include <thread>

class TokenBucket {
public:
    TokenBucket(int capacity, int refill_rate)
        : capacity_(capacity), refill_rate_(refill_rate), tokens_(capacity) {}

    bool try_consume(int tokens) {
        refill();
        if (tokens_ >= tokens) {
            tokens_ -= tokens;
            return true;
        }
        return false;
    }

private:
    void refill() {
        auto now = std::chrono::steady_clock::now();
        auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_refill_).count();
        int new_tokens = (elapsed * refill_rate_) / 1000;
        if (new_tokens > 0) {
            tokens_ = std::min(capacity_, tokens_ + new_tokens);
            last_refill_ = now;
        }
    }

    int capacity_;
    int refill_rate_; // tokens per second
    int tokens_;
    std::chrono::steady_clock::time_point last_refill_ = std::chrono::steady_clock::now();
};
